package titan.utils;

import java.io.File;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;

import titan.messages.Messages;

/**
 * Class that allows checkout of the content of a
 * SVN server directory to a local directory
 */
public class SVN {
	private String path;
	private String url;

	public SVN(String pathLocal, String urlLocal){
		path = pathLocal;
		url = urlLocal;
	}

	/**
	 * Does the SVN checkout from {@link SVN#url url} to {@link SVN#path path}
	 * @param statusBar - a {@link StatusBar} object to inform the function status.
	 * It can be null, if a {@link StatusBar} is not needed
	 * @throws Exception if the destination folder does not exist or if there was a problem while connecting
	 */
	public void checkout(StatusBar statusBar) throws Exception{
			File destination = new File(path);
			SVNURL url = null;
			if(!destination.exists())
				throw new Exception(Messages.CheckoutDestNFound+path);

			try {
				url = SVNURL.parseURIEncoded(this.url);
			} catch (Exception e) {
				throw new Exception(Messages.UnableConnect+this.url);
			}

			SVNClientManager cm = SVNClientManager.newInstance();
			SVNUpdateClient uc = cm.getUpdateClient();
			if(statusBar != null)
				statusBar.setText(Messages.DownFromSVN);
			try {
				uc.doCheckout(url, destination, SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, SVNDepth.INFINITY, true);
			} catch (Exception e) {
				throw new Exception(Messages.UnableCheckoutFrom+this.url+Messages.To+destination);
			}
	}
}